package com.flight.model.dao.impl;

import com.flight.model.dao.FlightDAO;
import com.flight.model.entity.Flight;
import com.flight.util.DBUtil;
import com.flight.util.DateUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 航班DAO实现类
 */
public class FlightDAOImpl implements FlightDAO {
    @Override
    public List<Flight> searchFlights(String depCity, String arrCity, Date depDate) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<Flight> flights = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            // 拼接SQL（按出发地、目的地、日期查询）
            String sql = "SELECT * FROM flight WHERE departure_city = ? AND arrival_city = ? AND departure_date = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, depCity);
            stmt.setString(2, arrCity);
            stmt.setString(3, DateUtil.formatDate(depDate));

            rs = stmt.executeQuery();
            while (rs.next()) {
                Flight flight = new Flight();
                flight.setFlightNo(rs.getString("flight_no"));
                flight.setDepartureCity(rs.getString("departure_city"));
                flight.setArrivalCity(rs.getString("arrival_city"));
                flight.setDepartureDate(DateUtil.parseDate(rs.getString("departure_date")));
                flight.setDepartureTime(DateUtil.parseTime(rs.getString("departure_time")));
                flight.setTotalSeats(rs.getInt("total_seats"));
                flight.setRemainingSeats(rs.getInt("remaining_seats"));
                flights.add(flight);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }
        return flights;
    }
}